<template>
	<view class="mall-container">
		<!-- 添加PLoader -->
		<PLoader :loading="loading" backgroundColor="rgba(255, 255, 255, 0.1)"></PLoader>

		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content">
				<view class="search-box">
					<uv-icon name="search" size="40" color="#666"></uv-icon>
					<input type="text" v-model="searchKeyword" placeholder="搜索商品" placeholder-class="placeholder"
						@input="debounceSearch" @confirm="handleSearch" confirm-type="search" />
					<view class="search-btn" @tap="handleSearch" v-if="searchKeyword">搜索</view>
				</view>
			</view>
		</view>

		<!-- 占位，防止内容被导航栏遮挡 -->
		<view class="navbar-placeholder" :style="{ height: navbarHeight + 'px' }"></view>

		<!-- 头部分类栏 -->
		<view class="category-header">
			<scroll-view class="category-scroll" scroll-x="true" show-scrollbar="false">
				<view class="category-scroll-content">
					<view class="category-item"
						  v-for="(item, index) in headerCategories"
						  :key="index"
						  :class="{ active: currentFirstLevelId === item.id }"
						  @tap="onHeaderCategoryTap(index)">
						<view class="icon-wrap">
							<image :src="item.icon || '/static/cycling.png'" mode="aspectFill" />
						</view>
						<view class="label">{{ item.name }}</view>
					</view>
				</view>
			</scroll-view>
		</view>


		<!-- 展开的分类网格 -->
		<view class="category-expand-grid" :class="{ 'show': isCategoryExpanded }">
			<view class="grid-content">
				<view class="category-grid-item"
					  v-for="(item, index) in headerCategories"
					  :key="index"
					  :class="{ active: currentFirstLevelId === item.id }"
					  @tap="onGridCategoryTap(index)">
					<view class="grid-icon-wrap">
						<image :src="item.icon || '/static/cycling.png'" mode="aspectFill" />
					</view>
					<view class="grid-label">{{ item.name }}</view>
				</view>
			</view>
			
			<!-- 收起按钮 - 在展开状态下显示在面板底部 -->
			<view class="expand-btn-container">
				<view class="expand-btn" @tap="toggleCategoryExpand" style="display: flex; align-items: center; justify-content: center; padding: 20rpx; background: rgba(255, 255, 255, 0.9); border: none; border-radius: 0; width: 100%; border-top: 1rpx solid rgba(255, 138, 95, 0.1); border-bottom: 1rpx solid rgba(255, 138, 95, 0.1);">
					<text style="font-size: 26rpx; color: #FF5733; margin-right: 8rpx; font-weight: 500;">收起</text>
					<uv-icon name="arrow-up" size="12" color="#FF5733"></uv-icon>
				</view>
			</view>
		</view>
		
		<!-- 展开按钮 - 在收起状态下显示 -->
		<view class="expand-btn-container" v-if="headerCategories.length >= 3 && !isCategoryExpanded">
			<view class="expand-btn" @tap="toggleCategoryExpand" style="display: flex; align-items: center; justify-content: center; padding: 20rpx; background: rgba(255, 255, 255, 0.9); border: none; border-radius: 0; width: 100%; border-top: 1rpx solid rgba(255, 138, 95, 0.1); border-bottom: 1rpx solid rgba(255, 138, 95, 0.1);">
				<text style="font-size: 26rpx; color: #FF5733; margin-right: 8rpx; font-weight: 500;">展开</text>
				<uv-icon name="arrow-down" size="12" color="#FF5733"></uv-icon>
			</view>
		</view>

		<!-- vtabs部分 -->
		<uv-vtabs
			:list="sideCategories"
			:current="currentCategoryIndex"
			:height="contentHeight"
			:hdHeight="500"
			:chain="false"
			barBgColor="linear-gradient(to top, rgba(255, 138, 95, 0.06), rgba(255, 138, 95, 0.02))"
			:barItemActiveStyle="{
				color: '#FF5733'
			}"
			:barItemActiveLineStyle="{
				background: '#FF5733'
			}"
			@scrolltolower="onScrollToLower"
			@change="onCategoryChange">
			<uv-vtabs-item>
				<view class="goods-list">
					<view v-for="item in goodsList" :key="item.id" class="goods-item" @click="goDetail(item)">
						<view class="goods-img">
							<image :src="item.mainImages[0].imageUrl" mode="aspectFill"></image>
						</view>
						<view class="goods-info">
							<view class="goods-title">{{ item.name }}</view>
							<view class="goods-desc" v-if="item.description">{{ item.description }}</view>
							<view class="goods-price-wrap">
								<view class="price-left">
									<!-- 现金支付 -->
									<view v-if="item.paymentType === 1" class="cash-price">
										<text class="currency">¥</text>
										<text class="price">{{ (item.price && item.price !== null && item.price !== undefined) ? Number(item.price).toFixed(2) : '0.00' }}</text>
									</view>
									<!-- 积分支付 -->
									<view v-if="item.paymentType === 2" class="points-price">
										<text class="points">{{ (item.points && item.points !== null && item.points !== undefined) ? item.points : 0 }}积分</text>
									</view>
									<!-- 积分+现金 -->
									<view v-if="item.paymentType === 3" class="mixed-payment">
										<text class="points">{{ (item.pointsCashPoints && item.pointsCashPoints !== null && item.pointsCashPoints !== undefined) ? item.pointsCashPoints : 0 }}积分</text>
										<view class="cash-part">
											<text class="currency">¥</text>
											<text class="price">{{ (item.pointsCashPrice && item.pointsCashPrice !== null && item.pointsCashPrice !== undefined) ? Number(item.pointsCashPrice).toFixed(2) : '0.00' }}</text>
										</view>
									</view>
									<!-- 礼品卡/券 -->
									<view v-if="item.paymentType === 4 || item.paymentType === 5" class="gift-payment">
										<text class="gift-text">{{ item.paymentType === 4 ? '礼品卡' : '礼品券' }}</text>
										<text class="gift-num">{{ item.paymentType === 4 ?
											((item.giftCardNum && item.giftCardNum !== null && item.giftCardNum !== undefined) ? item.giftCardNum : 0) :
											((item.giftVoucherNum && item.giftVoucherNum !== null && item.giftVoucherNum !== undefined) ? item.giftVoucherNum : 0) }}张</text>
									</view>
								</view>
								<view class="price-right">
									已售{{ (item.sales && item.sales !== null && item.sales !== undefined) ? item.sales : 0 }}
								</view>
							</view>
						</view>
					</view>
				</view>
				<uv-loadmore :status="loadStatus" v-if="!loading"></uv-loadmore>
			</uv-vtabs-item>
		</uv-vtabs>

		<!-- 空状态显示 -->
		<view class="empty" v-if="!loading && goodsList.length === 0 && !isCategoryExpanded">
			<uv-empty mode="car" text="暂无商品" textSize="28" iconSize="100"></uv-empty>
		</view>

		<CustomTabBar selected="1" />
	</view>
</template>

<script>
export default {
	data() {
		return {
			searchKeyword: '',
			goodsList: [],
			page: 1,
			loadStatus: 'loadmore',
			currentCategory: 0,
			categories: [],
			loading: true,
			statusBarHeight: 0,
			navbarHeight: 0,
			searchTimer: null,
			refreshing: false,
			currentCategoryIndex: 0,
			categoryLoadStatus: {},
			headerCategories: [], // 头部展示的一级分类
			sideCategories: [], // 侧边栏展示的二级分类
			currentFirstLevelId: null, // 当前选中的一级分类 ID
			isCategoryExpanded: false, // 是否展开分类网格
		}
	},

	computed: {
		contentHeight() {
			// 计算内容区域高度 = 屏幕高度 - 导航栏高度 - 底部tabbar高度
			const windowHeight = uni.getSystemInfoSync().windowHeight
			return windowHeight - this.navbarHeight - 50 // 50是底部tabbar的高度
		}
	},

	async onLoad() {
		this.initNavBarHeight()
		await this.fetchCategories()
	},

	methods: {
		async fetchCategories() {
			try {
				// 获取一级分类列表
				const res = await this.$http.get('/mall/category/first-level')
				if (res) {
					// 获取所有有图标的一级分类（不限制数量）
					this.headerCategories = res
						.filter(item => item.icon) // 只显示有图标的
						.map(item => ({
							id: item.id,
							name: item.name,
							icon: item.icon
						}));

					// 默认选中第一个一级分类
					if (this.headerCategories.length > 0) {
						this.currentFirstLevelId = this.headerCategories[0].id;
						await this.loadSecondLevelCategories(this.currentFirstLevelId);
					}
				}
			} catch (e) {
				console.error('获取分类列表失败:', e)
				uni.showToast({
					title: '获取分类列表失败',
					icon: 'none'
				})
			}
		},

		// 加载二级分类
		async loadSecondLevelCategories(parentId) {
			try {
				const res = await this.$http.get(`/mall/category/children?parentId=${parentId}`);
				if (res && res.length > 0) {
					// 有二级分类，显示二级分类列表
					this.sideCategories = res.map(item => ({
						id: item.id,
						name: item.name
					}));
					this.categories = this.sideCategories;

					// 默认选中第一个二级分类
					if (this.sideCategories.length > 0) {
						this.currentCategory = this.sideCategories[0].id;
						this.currentCategoryIndex = 0;
						this.resetList();
						this.getGoodsList(this.currentCategory);
					}
				} else {
					// 没有二级分类，直接显示一级分类下的商品
					this.sideCategories = [];
					this.categories = [];
					this.currentCategory = parentId;
					this.currentCategoryIndex = -1;
					this.resetList();
					this.getGoodsList(parentId);
				}
			} catch (e) {
				console.error('加载二级分类失败:', e);
				uni.showToast({
					title: '加载分类失败',
					icon: 'none'
				});
			}
		},

		// 侧边栏分类改变事件（二级分类）
		onCategoryChange(index) {
			if (this.sideCategories.length > 0) {
				const category = this.sideCategories[index];
				this.currentCategory = category.id;
				this.currentCategoryIndex = index;
				this.resetList();
				this.getGoodsList(category.id);
			}
		},

		resetList() {
			this.page = 1
			this.goodsList = []
			this.loadStatus = 'loadmore'
			if (this.page === 1) {
				this.loading = true
			}
		},

		async getGoodsList(categoryId) {
			this.loadStatus = 'loading'
			try {
				const params = {
					pageNum: this.page,
					pageSize: 10,
					categoryId: categoryId || this.currentCategory
				}
				if (this.searchKeyword) {
					params.name = this.searchKeyword
				}

				const res = await this.$http.post('/mall/goods/list', params)
				if (res) {
					const goodsList = res.items || []
					const currentTotal = this.goodsList.length + goodsList.length

					if (goodsList.length > 0) {
						// 处理商品数据，确保价格字段有默认值
						const processedGoodsList = goodsList.map(item => ({
							...item,
							price: item.price || 0,
							points: item.points || 0,
							pointsCashPoints: item.pointsCashPoints || 0,
							pointsCashPrice: item.pointsCashPrice || 0,
							giftCardNum: item.giftCardNum || 0,
							giftVoucherNum: item.giftVoucherNum || 0,
							sales: item.sales || 0
						}))

						this.goodsList.push(...processedGoodsList)
						this.loadStatus = currentTotal < res.count ? 'loadmore' : 'nomore'
					} else {
						this.loadStatus = 'nomore'
						if (this.page === 1) {
							this.goodsList = []
						}
					}
				}
			} catch (e) {
				this.loadStatus = 'loadmore'
				uni.showToast({
					title: '获取商品列表失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},

		onSearch() {
			this.page = 1
			this.goodsList = []
			this.loading = true
			this.getGoodsList(this.currentCategory)
		},

		goDetail(item) {
			uni.navigateTo({
				url: `/subpkg/mall_good_detail/mall_good_detail?goodsId=${item.id}&categoryId=${item.categoryId}`
			})
		},

		// 初始化导航栏高度
		initNavBarHeight() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight
			// 计算导航栏高度 (状态栏 + 44px)
			this.navbarHeight = this.statusBarHeight + 44
		},

		// 防抖搜索方法
		debounceSearch(e) {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
			}
			this.searchTimer = setTimeout(() => {
				this.handleSearch()
			}, 500) // 500ms延迟
		},

		// 处理搜索
		handleSearch() {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
			}
			this.onSearch()
		},

		// 添加刷新方法
		async onRefresh() {
			this.refreshing = true
			try {
				this.resetList()
				await this.getGoodsList()
			} finally {
				this.refreshing = false
			}
		},

		// 滚动到底部的处理
		onScrollToLower() {
			if (this.loadStatus === 'loadmore' && !this.loading) {
				this.page++
				this.getGoodsList(this.currentCategory)
			}
		},

		// 头部分类点击事件（一级分类）
		async onHeaderCategoryTap(index) {
			// 防止重复点击
			if (this.loading) {
				return;
			}

			const category = this.headerCategories[index];

			// 如果点击的是当前已选中的分类，则不重复加载
			if (this.currentFirstLevelId === category.id) {
				return;
			}

			this.currentFirstLevelId = category.id;

			// 加载该一级分类下的二级分类
			await this.loadSecondLevelCategories(category.id);
		},

		// 展开/收起分类网格
		toggleCategoryExpand() {
			this.isCategoryExpanded = !this.isCategoryExpanded;
		},

		// 网格内分类点击事件
		async onGridCategoryTap(index) {
			// 防止重复点击
			if (this.loading) {
				return;
			}

			const category = this.headerCategories[index];

			// 如果点击的是当前已选中的分类，则不重复加载
			if (this.currentFirstLevelId === category.id) {
				return;
			}

			this.currentFirstLevelId = category.id;

			// 加载该一级分类下的二级分类
			await this.loadSecondLevelCategories(category.id);
		},
	},

	onReady() {
		this.loading = false
	}
}
</script>

<style lang="scss" scoped>
@import 'shop.scss';

// 修改搜索框样式
.search-box {
	display: flex;
	align-items: center;
	background: #f5f7ff;
	height: 64rpx;
	border-radius: 32rpx;
	padding: 0 24rpx;
	width: 450rpx;

	input {
		flex: 1;
		height: 100%;
		margin-left: 16rpx;
		font-size: 26rpx;
	}

	.placeholder {
		color: #999;
	}

	.search-btn {
		padding: 0 20rpx;
		height: 48rpx;
		line-height: 48rpx;
		background: $uni-color-primary;
		color: #fff;
		font-size: 24rpx;
		border-radius: 24rpx;
		margin-left: 16rpx;

		&:active {
			opacity: 0.8;
		}
	}
}

.category-header {
	padding: 30rpx 20rpx;
	background: linear-gradient(to bottom, rgba(255, 138, 95, 0.06), rgba(255, 138, 95, 0.02));
	box-shadow: 0 2rpx 12rpx rgba(255, 138, 95, 0.05);
	width: 100%;
	display: flex;
	align-items: center;
	gap: 20rpx;

	.category-scroll {
		flex: 1;
		white-space: nowrap;

		.category-scroll-content {
			display: flex;
			align-items: center;
			padding: 0 40rpx;
			min-width: max-content;
		}
	}

	.category-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
		margin-right: 50rpx;
		flex-shrink: 0;
		transition: all 0.3s ease;

		&:last-child {
			margin-right: 30rpx;
		}

		.icon-wrap {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			overflow: hidden;
			margin-bottom: 12rpx;
			border: 3rpx solid transparent;
			transition: all 0.3s ease;

			image {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
		}

		.label {
			padding: 4rpx 16rpx;
			background: linear-gradient(to right, $mall-primary-100, $mall-primary-200);
			border-radius: 20rpx;
			font-size: 22rpx;
			color: #fff;
			transition: transform 0.3s ease;
			white-space: nowrap;
			text-align: center;
		}

		// 选中状态
		&.active {
			.icon-wrap {
				border-color: $mall-primary-100;
				box-shadow: 0 0 12rpx rgba($mall-primary-100, 0.2);
			}

			.label {
				transform: scale(1.05);
			}
		}

		&:active {
			opacity: 0.8;
		}
	}
}

.expand-btn-container {
	display: flex;
	justify-content: center;
	padding: 0;
	background: linear-gradient(to bottom, rgba(255, 138, 95, 0.06), rgba(255, 138, 95, 0.02));
}

.expand-btn {
	display: flex !important;
	flex-direction: row !important;
	align-items: center !important;
	justify-content: center !important;
	padding: 20rpx;
	background: rgba(255, 255, 255, 0.9);
	border: none;
	border-radius: 0;
	width: 100%;
	transition: all 0.3s ease;
	box-shadow: none;
	border-top: 1rpx solid rgba(255, 138, 95, 0.1);
	border-bottom: 1rpx solid rgba(255, 138, 95, 0.1);

	text {
		font-size: 26rpx;
		color: #666;
		margin-right: 8rpx;
		font-weight: 500;
		display: inline-block;
	}

	&:active {
		opacity: 0.8;
		background: rgba(255, 138, 95, 0.1);
	}
}

// 展开的分类网格
.category-expand-grid {
	background: #fff;
	overflow: hidden;
	max-height: 0;
	transition: max-height 0.3s ease;

	&.show {
		max-height: 800rpx;
	}

	.grid-content {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 20rpx;
		padding: 30rpx 20rpx;
		background: linear-gradient(to bottom, rgba(255, 138, 95, 0.06), rgba(255, 138, 95, 0.02));
	}

	.category-grid-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		transition: all 0.3s ease;

		.grid-icon-wrap {
			width: 90rpx;
			height: 90rpx;
			border-radius: 50%;
			overflow: hidden;
			margin-bottom: 10rpx;
			border: 3rpx solid transparent;
			transition: all 0.3s ease;

			image {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
		}

		.grid-label {
			padding: 4rpx 12rpx;
			background: linear-gradient(to right, $mall-primary-100, $mall-primary-200);
			border-radius: 16rpx;
			font-size: 20rpx;
			color: #fff;
			transition: transform 0.3s ease;
			white-space: nowrap;
			text-align: center;
		}

		// 选中状态
		&.active {
			.grid-icon-wrap {
				border-color: $mall-primary-100;
				box-shadow: 0 0 12rpx rgba($mall-primary-100, 0.2);
			}

			.grid-label {
				transform: scale(1.05);
			}
		}

		&:active {
			opacity: 0.8;
		}
	}

	.collapse-btn {
		display: flex !important;
		flex-direction: row !important;
		align-items: center !important;
		justify-content: center !important;
		padding: 16rpx 24rpx;
		background: rgba(255, 255, 255, 0.9);
		border: 1rpx solid #e0e0e0;
		border-radius: 24rpx;
		margin: 20rpx auto 0;
		width: auto;
		min-width: 160rpx;
		transition: all 0.3s ease;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

		text {
			font-size: 26rpx;
			color: #666;
			margin-right: 8rpx;
			font-weight: 500;
			display: inline-block;
		}

		&:active {
			opacity: 0.8;
			transform: scale(0.95);
		}
	}
}
</style>
